package coreservlets;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SearchEngines extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse response)
			throws ServletException, IOException {
		String searchString = req.getParameter("searchString");
		if (searchString == null || searchString.isEmpty()) {
			reportProblem(response, "Missing search engine name");
			return;
		}
		searchString = URLEncoder.encode(searchString);

		String searchEngineName = req.getParameter("searchEngine");
		if ((searchEngineName == null) || (searchEngineName.length() == 0)) {
			reportProblem(response, "Missing search engine name");
			return;
		}
		String searchURL = SearchUtilities.makeURL(searchEngineName, searchString);
		if (searchURL != null) {
			response.sendRedirect(searchURL);
		} else {
			reportProblem(response, "Unrecognized search engine");
		}

	}

	private void reportProblem(HttpServletResponse response, String message)
			throws IOException {
		response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
	}

}
